import React, { useState, useRef, useEffect } from 'react';

interface Message {
  id: string;
  sender: 'user' | 'ai';
  content: string;
  timestamp: Date;
}

const AIChatPage: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      sender: 'ai',
      content: '你好呀!我是你的AI助手~有什么可以帮你的吗？😊',
      timestamp: new Date(),
    },
  ]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // AI回复逻辑（支持更多场景）
  const fetchAIReply = async (userInput: string) => {
    setIsLoading(true);
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 800));

      let aiReply = '';
      if (userInput.includes('天气')) {
        aiReply = '今天天气晴朗,温度25-32℃,适合出门玩耍哦～ 记得涂防晒呀！☀️';
      } else if (userInput.includes('闹钟')) {
        aiReply = '已为你设置明天7:00的闹钟~ 早睡早起身体好！⏰ 如需修改时间可以告诉我哦～';
      } else if (userInput.includes('应用')) {
        aiReply = '常用应用有:微信、QQ、抖音、网易云音乐、快手~ 点击应用库即可快速打开！📱';
      } else if (userInput.includes('你好') || userInput.includes('hi') || userInput.includes('哈喽')) {
        aiReply = '哈喽～ 很高兴见到你！有什么需求都可以跟我说呀～ 😊 我可以帮你查天气、设闹钟、打开应用哦！';
      } else if (userInput.includes('时间') || userInput.includes('日期')) {
        const now = new Date();
        const dateStr = now.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });
        const timeStr = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        aiReply = `现在是${dateStr}，时间${timeStr}~ ⏱️`;
      } else if (userInput.includes('音乐') || userInput.includes('听歌')) {
        aiReply = '已为你打开网易云音乐～ 想听什么歌可以告诉我，我帮你搜索呀！🎵';
      } else {
        aiReply = `哇！你说"${userInput}"~ 我收到啦～ 如果你有具体需求（比如查天气、设闹钟），我可以更好地帮助你哦！💪`;
      }

      setMessages((prev) => [
        ...prev,
        {
          id: Date.now().toString(),
          sender: 'ai',
          content: aiReply,
          timestamp: new Date(),
        },
      ]);
    } catch {
      setMessages((prev) => [
        ...prev,
        {
          id: Date.now().toString(),
          sender: 'ai',
          content: '抱歉呀，我暂时无法回复你的消息，请稍后再试～ 😥',
          timestamp: new Date(),
        },
      ]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSendMessage = () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      sender: 'user',
      content: inputValue,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInputValue('');
    fetchAIReply(inputValue.trim());
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isLoading) {
      handleSendMessage();
    }
  };

  return (
    <div
      style={{
        marginLeft: '0',
        height: '100vh',
        background: 'linear-gradient(135deg, #fff5f7 0%, #fdf2f8 100%)',
        color: '#333',
        display: 'flex',
        flexDirection: 'column',
        padding: '2%',
        boxSizing: 'border-box',
        overflowX: 'hidden',
        fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
      }}
    >
      <div
        style={{
          padding: '16px 24px',
          background: 'rgba(255, 221, 233, 0.95)',
          borderBottom: '1px solid rgba(255, 182, 193, 0.3)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          borderRadius: '16px 16px 0 0',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
        }}
      >
        <h2 style={{ margin: 0, color: '#881337', fontSize: '20px', fontWeight: 600 }}>
          🌸 粉色AI助手
        </h2>
        <div style={{ display: 'flex', gap: '12px' }}>
          <button
            style={{
              background: 'transparent',
              border: '1px solid #d946ef',
              color: '#d946ef',
              borderRadius: '6px',
              padding: '6px 12px',
              cursor: 'pointer',
              fontSize: '14px',
              transition: 'all 0.2s',
              fontWeight: 500,
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(217, 70, 239, 0.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
            }}
          >
            缩小
          </button>
          <button
            style={{
              background: 'transparent',
              border: '1px solid #d946ef',
              color: '#d946ef',
              borderRadius: '6px',
              padding: '6px 12px',
              cursor: 'pointer',
              fontSize: '14px',
              transition: 'all 0.2s',
              fontWeight: 500,
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(217, 70, 239, 0.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
            }}
          >
            关闭
          </button>
        </div>
      </div>

      <div
        style={{
          flex: 1,
          padding: '24px',
          overflowY: 'auto',
          display: 'flex',
          flexDirection: 'column',
          gap: '20px',
          background: 'white',
          borderRadius: '0 0 16px 16px',
          margin: '10px 0',
          boxShadow: 'inset 0 2px 8px rgba(0, 0, 0, 0.03)',
        }}
      >
        {messages.map((msg) => (
          <div
            key={msg.id}
            style={{
              maxWidth: '80%',
              alignSelf: msg.sender === 'user' ? 'flex-end' : 'flex-start',
              display: 'flex',
              flexDirection: 'column',
              gap: '6px',
              animation: 'fadeIn 0.3s ease-out',
            }}
          >
            <div
              style={{
                padding: '14px 18px',
                borderRadius: msg.sender === 'user' ? '18px 6px 18px 18px' : '6px 18px 18px 18px',
                background: msg.sender === 'user' 
                  ? 'linear-gradient(135deg, #ec4899 0%, #d946ef 100%)' 
                  : 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                color: msg.sender === 'user' ? 'white' : '#333',
                boxShadow: msg.sender === 'user' 
                  ? '0 4px 12px rgba(217, 70, 239, 0.25)' 
                  : '0 4px 12px rgba(224, 242, 254, 0.5)',
                fontSize: '15px',
                lineHeight: 1.5,
                position: 'relative',
                transform: 'translateZ(0)', // 触发硬件加速
                transition: 'all 0.2s ease',
              }}
            >
              {msg.content}
              {/* 气泡小尾巴 */}
              <div
                style={{
                  position: 'absolute',
                  bottom: '-6px',
                  left: msg.sender === 'user' ? 'auto' : '20px',
                  right: msg.sender === 'user' ? '20px' : 'auto',
                  width: '12px',
                  height: '12px',
                  background: msg.sender === 'user' 
                    ? 'linear-gradient(135deg, #ec4899 0%, #d946ef 100%)' 
                    : 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                  clipPath: msg.sender === 'user' ? 'polygon(0 0, 100% 0, 100% 100%)' : 'polygon(0 0, 100% 0, 0 100%)',
                }}
              />
            </div>
            <span
              style={{
                fontSize: '12px',
                color: '#999',
                alignSelf: msg.sender === 'user' ? 'flex-end' : 'flex-start',
                paddingLeft: msg.sender === 'user' ? '0' : '10px',
                paddingRight: msg.sender === 'user' ? '10px' : '0',
              }}
            >
              {msg.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </span>
          </div>
        ))}
        {isLoading && (
          <div 
            style={{ 
              alignSelf: 'flex-start', 
              display: 'flex', 
              flexDirection: 'column',
              gap: '6px',
            }}
          >
            <div 
              style={{
                padding: '14px 18px',
                borderRadius: '6px 18px 18px 18px',
                background: 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                color: '#333',
                boxShadow: '0 4px 12px rgba(224, 242, 254, 0.5)',
                fontSize: '15px',
                lineHeight: 1.5,
                position: 'relative',
              }}
            >
              <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                <div 
                  style={{
                    width: '8px',
                    height: '8px',
                    borderRadius: '50%',
                    background: '#d946ef',
                    animation: 'pulse 1.5s infinite ease-in-out',
                  }}
                />
                <div 
                  style={{
                    width: '8px',
                    height: '8px',
                    borderRadius: '50%',
                    background: '#d946ef',
                    animation: 'pulse 1.5s infinite ease-in-out',
                    animationDelay: '0.2s',
                  }}
                />
                <div 
                  style={{
                    width: '8px',
                    height: '8px',
                    borderRadius: '50%',
                    background: '#d946ef',
                    animation: 'pulse 1.5s infinite ease-in-out',
                    animationDelay: '0.4s',
                  }}
                />
              </div>
              {/* 气泡小尾巴 */}
              <div
                style={{
                  position: 'absolute',
                  bottom: '-6px',
                  left: '20px',
                  width: '12px',
                  height: '12px',
                  background: 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                  clipPath: 'polygon(0 0, 100% 0, 0 100%)',
                }}
              />
            </div>
            <span
              style={{
                fontSize: '12px',
                color: '#999',
                alignSelf: 'flex-start',
                paddingLeft: '10px',
              }}
            >
              正在输入...
            </span>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div
        style={{
          padding: '16px 24px',
          borderTop: '1px solid rgba(255, 182, 193, 0.3)',
          background: 'rgba(255, 255, 255, 0.95)',
          display: 'flex',
          gap: '12px',
          alignItems: 'center',
          borderRadius: '16px',
          boxShadow: '0 -2px 10px rgba(0, 0, 0, 0.05)',
        }}
      >
        <button
          style={{
            background: 'rgba(255, 221, 233, 0.9)',
            border: 'none',
            borderRadius: '50%',
            width: '44px',
            height: '44px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            color: '#d946ef',
            fontSize: '20px',
            transition: 'all 0.2s',
            boxShadow: '0 2px 6px rgba(0, 0, 0, 0.1)',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = 'rgba(255, 221, 233, 1)';
            e.currentTarget.style.transform = 'scale(1.05)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = 'rgba(255, 221, 233, 0.9)';
            e.currentTarget.style.transform = 'scale(1)';
          }}
        >
          🎙️
        </button>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="输入你的问题，按回车发送..."
          style={{
            flex: 1,
            padding: '14px 18px',
            border: '1px solid rgba(255, 182, 193, 0.3)',
            borderRadius: '26px',
            outline: 'none',
            fontSize: '15px',
            background: 'rgba(255, 255, 255, 0.9)',
            color: '#333',
            transition: 'all 0.2s',
            boxShadow: 'inset 0 1px 4px rgba(0, 0, 0, 0.05)',
          }}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = '#d946ef';
            e.currentTarget.style.boxShadow = '0 0 0 2px rgba(217, 70, 239, 0.2)';
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = 'rgba(255, 182, 193, 0.3)';
            e.currentTarget.style.boxShadow = 'inset 0 1px 4px rgba(0, 0, 0, 0.05)';
          }}
        />
        <button
          onClick={handleSendMessage}
          disabled={isLoading || !inputValue.trim()}
          style={{
            background: isLoading || !inputValue.trim() 
              ? 'rgba(217, 70, 239, 0.5)' 
              : 'linear-gradient(135deg, #ec4899 0%, #d946ef 100%)',
            border: 'none',
            borderRadius: '26px',
            padding: '14px 26px',
            color: 'white',
            cursor: isLoading || !inputValue.trim() ? 'not-allowed' : 'pointer',
            fontSize: '15px',
            fontWeight: 600,
            transition: 'all 0.2s',
            boxShadow: isLoading || !inputValue.trim() 
              ? 'none' 
              : '0 4px 12px rgba(217, 70, 239, 0.3)',
          }}
          onMouseEnter={(e) => {
            if (!isLoading && inputValue.trim()) {
              e.currentTarget.style.transform = 'translateY(-2px)';
              e.currentTarget.style.boxShadow = '0 6px 16px rgba(217, 70, 239, 0.4)';
            }
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'translateY(0)';
            e.currentTarget.style.boxShadow = isLoading || !inputValue.trim() 
              ? 'none' 
              : '0 4px 12px rgba(217, 70, 239, 0.3)';
          }}
        >
          {isLoading ? '发送中...' : '发送'}
        </button>
      </div>
    </div>
  );
};

export default AIChatPage;

// 添加响应式CSS样式和动画
const style = document.createElement('style');
style.innerHTML = `
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  @keyframes pulse {
    0%, 100% {
      transform: scale(1);
      opacity: 1;
    }
    50% {
      transform: scale(1.2);
      opacity: 0.7;
    }
  }
  
  @media (max-width: 768px) {
    .message-bubble {
      max-width: 85% !important;
    }
    
    .input-container {
      flex-direction: column !important;
      gap: 10px !important;
    }
    
    .input-container input {
      width: 100% !important;
    }
    
    .input-container button {
      width: 100% !important;
      padding: 10px !important;
    }
  }
  
  @media (max-width: 480px) {
    .message-bubble {
      max-width: 90% !important;
      font-size: 13px !important;
    }
    
    .message-bubble div {
      padding: 10px 14px !important;
    }
    
    .header-buttons {
      flex-direction: column !important;
      gap: 5px !important;
    }
    
    .header-buttons button {
      padding: 2px 6px !important;
      font-size: 12px !important;
    }
  }
`;
document.head.appendChild(style);